package web.java.z_Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
	private static String url=null;
	private static String username=null;
	private static String password=null;
	private static String classDriver=null;
	static {
		Properties properties=new Properties();
		/*String path=DBUtils.class.getResource("/db.properties").getPath();
		File file=new File(path);
		InputStream in=new FileInputStream(file);*/
		InputStream in=DBUtils.class.getResourceAsStream("/db.properties");
		try {
			properties.load(in);
			url=properties.getProperty("url");
			username=properties.getProperty("username");
			password=properties.getProperty("password");
			classDriver=properties.getProperty("classDriver");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 返回数据库连接对象
	 * */
	public static Connection getConnection(){
		Connection conn=null;
		try {
			Class.forName(classDriver);
			conn=DriverManager.getConnection(url,username,password);
			return conn;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 关闭数据库
	 * */
	public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet result){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			if(pstmt!=null){
				try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(result!=null){
				try {
					result.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public static void closeAll(Connection conn, PreparedStatement pstmt){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			if(pstmt!=null){
				try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
